﻿using ExchangeClient.Abstractions;
using ExchangeClient.Abstractions.Model;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.XWPF.UserModel;
using Org.BouncyCastle.Math.EC.Rfc7748;
using SyncService.Abstractions.Events;
using SyncService.Abstractions.Services;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

namespace SyncService.Core.Services
{
    [Export(typeof(ISyncService))]
    [ExportMetadata(YdConstants.ID, "freeUpBudget")]
    public class FreeUpBudget : AssetSyncServiceBase
    {
        private IMemoryCache? _cache = null;
        private ILogger<FreeUpBudget> _logger = null;
        public FreeUpBudget() : base(YdConstants.YIDEA, "Esb", "")
        {
        }
        protected override void InitializeContext()
        {
            base.InitializeContext();
            _cache = Resolver.Resolve<IMemoryCache>();
            _logger = Resolver.Resolve<ILogger<FreeUpBudget>>();
        }
        public override void ExecuteCore()
        {
            JsonObject jsonObject = JsonNode.Parse(State.Body)!.AsObject();
            var Data = jsonObject["data"].AsObject();

            _logger.LogInformation("释放预算流水号：" + Data["SerialNo"]);
            var detailListField = ExtendFields.Where(e => e.ObjectType == 54 && e.Name == "申请明细").First();
            var dateField = ExtendFields.Where(e => e.ObjectType == 54 && e.Name == "释放日期").First();
            var fKApplicationNoField = ExtendFields.Where(e => e.ObjectType == 54 && e.Name == "费控申请单号").First();
            var feeSubclassField = ExtendFields.Where(e => e.ObjectType == 54 && e.Name == "费用小类").First();

            var centerField = ExtendFields.Where(e => e.ObjectType == 54 && e.Name == "成本中心").First();
            var amountField = ExtendFields.Where(e => e.ObjectType == 54 && e.Name == "金额").First();
            JsonArray dataList = Data[detailListField.FieldId].AsArray();
            foreach (var item in dataList)
            {
                CustomizedFormData customizedFormData = new CustomizedFormData();
                customizedFormData.Data = new System.Text.Json.Nodes.JsonObject()
                {
                    ["Date"] = Data[dateField.FieldId].ToString(),
                    ["FKApplicationNo"]=Data[fKApplicationNoField.FieldId].ToString(),
                    ["FeeSubclass"]=item[feeSubclassField.FieldId].ToString(),
                    ["CenterCode"]=item[centerField.FieldId].ToString(),
                    ["Amount"]=item[amountField.FieldId].ToString(),
                    ["SerialNo"] = Data["SerialNo"].ToString()
                };
                
                ToClient.AddNewCustomizedFormData(customizedFormData);
            }
        }
        }
}
